package com.intel.factorytest.activity;

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set; 
import java.util.Timer;
import java.util.TimerTask;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.intel.factorytest.R;
import com.intel.factorytest.application.MATApplication;
import com.intel.factorytest.cfparser.ConfigFileParseUtil;
import com.intel.factorytest.cfparser.concrete.AConfigFileParser;
import com.intel.factorytest.cfparser.concrete.PropertiesConfParser;
import com.intel.factorytest.log.LogWriter;

public class WifiAndBluetooth extends BaseActivity {
    private static final String TAG = "WifiAndBluetooth";
//    private static final int MAX_COUNT_DEV_DISPLAY = 5;
    private static final int MAX_COUNT_DEV_DISPLAY = 3;
    
    private static final String TAG_WIFI_BT = "WifiAndBlutooth";
    private static final String TAG_WIFI = "WIFI";
    private static final String TAG_BT = "Bluetooth";
    
    private static final String TAG_WIFI_BT_zh = "WIFI和蓝牙测试";
    private static final String TAG_WIFI_zh = "WIFI测试";
    private static final String TAG_BT_zh = "蓝牙测试";
    
    private static final int BT_NODEFINE_BASE_LINE = 70;
    private static final int WIFI_NODEFINE_BASE_LINE = 70;
    
    private static final Map<String, String> nameMapping_language = new HashMap<String, String>();
    static {
        nameMapping_language.put(TAG_WIFI_BT, TAG_WIFI_BT_zh);
        nameMapping_language.put(TAG_WIFI, TAG_WIFI_zh);
        nameMapping_language.put(TAG_BT, TAG_BT_zh);
    }
    
    // Handler Message
    private static final int MSG_CHECK_RESULT = 1;
     
    // Timer
    private Timer mTimer_CheckResult = null;
    
    // properties
    private Properties properties;
    
    // test result
    private boolean resultWifiOK = false;
    private boolean resultBTOK = false;
    
    private boolean mCanScanWIFI = false;
    private boolean mCanScanBT = false;
    
    // properties key
    private static final String KEY_WIFI_SSID = "WIFI_SSID";
    private static final String KEY_WIFI_RSSI = "WIFI_RSSI";
    private static final String KEY_WIFI_RSSI_ERROR_LIMITATION = "WIFI_RSSI_ERROR_LIMITATION";
    
    private static final String KEY_BT_SSID = "BT_SSID";
    private static final String KEY_BT_RSSI = "BT_RSSI";
    private static final String KEY_BT_RSSI_ERROR_LIMITATION = "BT_RSSI_ERROR_LIMITATION";
    // properties value
    private String valueWifiSsid; // properties.get(KEY_WIFI_SSID);
    private String valueWifiRssi; // properties.get(KEY_WIFI_RSSI);
    private int valueWifiRssiErrorLimitation = 10; // default value (dbm)
    private String[] ssidsWifi;
    private String[] rssisWifi;
    
    private String valueBTSsid;
    private String valueBTRssi;
    private int valueBTRssiErrorLimitation = 10;
    private String[] ssidsBT;
    private String[] rssisBT;
    
    // #####  WIFI  #####
    private WifiManager mWifiManager = null;
    private static final int SET_WIFI_STATUS = 1;
    private Timer mTimer_Wifi;
    private IntentFilter mFilter_Wifi = null;
    private Scanner mScanner_Wifi;
    private BroadcastReceiver mReceiver_Wifi;
    private TextView wifiLabelText = null;
    private TextView wifiInfosTv = null;
    Handler mHandler_Wifi = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == SET_WIFI_STATUS) {

                mWifiManager.setWifiEnabled(true);
            }

        }
    };
    
    private boolean isCheckedWIFI = false;
    private boolean isCheckedBT = false;
    
    //  ######  Bluetooth  #########
    private BluetoothAdapter mAdapter_BT = null; 
    private static final int SET_BT_STATUS = 1;
    private Timer mTimer_BT;
    private IntentFilter mFilter_BT = null;
        private BroadcastReceiver mReceiver_BT;
    private TextView btLabelText = null;
    private TextView btDevInfosTv = null;
    private long mLastScan;
    private int mdeviceCount_BT = 0;
    private String mBTDevicesInfo = "";
    private static final int SCAN_EXPIRATION_MS = 10 * 1000;
    Handler mHandler_BT = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(msg.what == SET_BT_STATUS){
                if(BluetoothAdapter.STATE_ON != mAdapter_BT.getState()) {
                    mAdapter_BT.enable();
                } else {
                    startScanning(true);
                }
            }

        }
    }; 
    
    boolean isExistAll_wifi = false;
//    boolean isSsidBeyondLimit_wifi = false;
    boolean isWIFISsidTestOK = false;
    
    boolean isExistAll_bt = false;
//    boolean isSsidBeyondLimit_bt = false;
    boolean isBTSsidTestOK = false;

    private boolean isWifiScanned = false;

    protected void onCreate(android.os.Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // load properties configuration file
        
        properties = ((PropertiesConfParser) ConfigFileParseUtil.getConfParserConcrete(this, AConfigFileParser.EXTENSION_PROPERTISE)).getProperties(isPcba);
        valueWifiSsid = properties.getProperty(KEY_WIFI_SSID);
        valueWifiRssi = properties.getProperty(KEY_WIFI_RSSI);
        valueWifiRssiErrorLimitation = Integer.parseInt(properties.getProperty(KEY_WIFI_RSSI_ERROR_LIMITATION));
        ssidsWifi = valueWifiSsid.split(";");
         rssisWifi = valueWifiRssi.split(";");
         
         valueBTSsid = properties.getProperty(KEY_BT_SSID);
         valueBTRssi = properties.getProperty(KEY_BT_RSSI);
         Log.i("TAG", "valueBTSsid = " + valueBTSsid+"valueBTRssi:"+valueBTRssi);
         valueBTRssiErrorLimitation = Integer.parseInt(properties.getProperty(KEY_BT_RSSI_ERROR_LIMITATION));
         ssidsBT = valueBTSsid.split(";");
         rssisBT = valueBTRssi.split(";");
        
        setContentView(R.layout.wifi_bluetooth);
        initView();
        
        mFilter_Wifi = new IntentFilter();
        mFilter_Wifi.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        mFilter_Wifi.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
        mReceiver_Wifi = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (!isCheckedWIFI) {
                    handleWifiEvent(context, intent);
                }
            }
        };

        mScanner_Wifi = new Scanner();
        mWifiManager = (WifiManager) this
                .getSystemService(Context.WIFI_SERVICE);

        mFilter_BT = new IntentFilter();
        mFilter_BT.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        mFilter_BT.addAction(BluetoothDevice.ACTION_FOUND);
        mFilter_BT.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        //mFilter_BT.addAction(BluetoothDevice.ACTION_DISAPPEARED);
        mFilter_BT.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        mReceiver_BT = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (!isCheckedBT) {
                    handleBluetoothEvent(context, intent);
                }
            }
        };

        mAdapter_BT = BluetoothAdapter.getDefaultAdapter();
        
    }
    
    protected void initView() {
        wifiLabelText = (TextView) findViewById(R.id.wifiTextView);
        wifiLabelText.setText(this.getString(R.string.WIFI_TITLE));
        
        btLabelText = (TextView) findViewById(R.id.btTextView);
        btLabelText.setText(this.getString(R.string.BT_TITLE));
        
        wifiInfosTv = (TextView) findViewById(R.id.wifiInfos);
        btDevInfosTv = (TextView) findViewById(R.id.btDevInfos);
        btDevInfosTv.setText(this.getString(R.string.SERVICEMENU_BT_OPEN_TXT));
        
        mSucBtn = (Button) findViewById(R.id.success_button);
        if (isSystemTest)
        {
            mSucBtn.setVisibility(View.INVISIBLE);
        }
        
        mFailBtn = (Button) findViewById(R.id.fail_button);
        mRepeatBtn = (Button) findViewById(R.id.repeat_button);
        
//        mSucBtn.setAlpha(30);
//        mFailBtn.setAlpha(30);
//        mRepeatBtn.setAlpha(30);
        
        attachListener();
    }
    
    private void attachListener() {
        mSucBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                is_pass = true;
                finish();
            }
        });
        attachOnTouchListener(mSucBtn);

        mFailBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                is_pass = false;
                finish();
            }
        });
        attachOnTouchListener(mFailBtn);
        
        mRepeatBtn.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                WifiAndBluetooth.this.recreate();
            }
        });
        attachOnTouchListener(mRepeatBtn);
    }
    
    private Handler mHandler_CheckResult = new Handler() {

        @Override
        public void handleMessage(Message msg) {

            // update is_pass
            if (isWifiAndBTTestOK()) {
                is_pass = true;
            } else {
                is_pass = false;
            }

            switch (msg.what) {
            case MSG_CHECK_RESULT:
                if (is_pass) {
                    finish();
                } else {
                    if (mCanScanWIFI&&mCanScanBT){
                        //mSucBtn.setVisibility(View.VISIBLE);
                        is_pass = true;
                        finish();
                    }
                    else
                    {
                        
                    }
                    mFailBtn.setVisibility(View.VISIBLE);
                    mFailBtn.setEnabled(true);
                    //mFailBtn.setBackgroundColor(Color.WHITE);//remove by wagnsm
                }
                break;
            default:
                break;
            }

        }

    };
     
     private boolean checkWifiErrorResult(String ssid, int rssi) {
         
         rssi = Math.abs(rssi);
         
         boolean ssidExist = false;
         int compareRssi = 0;
         for (int i = 0; i < ssidsWifi.length; i++) {
            if (ssid.equals(ssidsWifi[i])) {
                compareRssi = Math.abs(Integer.parseInt(rssisWifi[i]));
                ssidExist = true;
            }
        }
         
         // 对于不在配置文件列表中的Wifi不做检查, 直接返回true.
         if (!ssidExist) {
             return true;
         }
         
//         return Math.abs(rssi - compareRssi) <= valueWifiRssiErrorLimitation;
         return Math.abs(compareRssi)>Math.abs(rssi)?true:false;    
     }
     
     private boolean checkAllWifiSsidExist(String[] ssids, List<ScanResult> scanResults) {
         // empty string
         if (ssidsWifi != null && ssidsWifi.length == 1 && ssidsWifi[0].trim().length() == 0) {
            return true;
        }
         
         for (String ssid : ssids) {
             boolean isExist = false;
            for (ScanResult scanResult : scanResults) {
                if (scanResult.SSID.equals(ssid)) {
                    isExist = true;
                }
            }
            if (!isExist) {
                return false;
            }
        }
         return true;
     }
     
     
     /**
      * 检查SSID and RSSI的数量是否一致
      * @return
      */
     private boolean checkWifiFormat() {
         if (valueWifiSsid == null || valueWifiSsid.trim().length() == 0 
                 || valueWifiRssi == null || valueWifiRssi.trim().length() == 0) {
             return false;
         }
         if (ssidsWifi.length != rssisWifi.length) {
             return false;
         }
         return true;
     }
     
     private boolean checkBTFormat() {
         if (valueBTSsid == null || valueBTSsid.trim().length() == 0 
                 || valueBTRssi == null || valueBTRssi.trim().length() == 0) {
             return false;
         }
         if (ssidsBT.length != rssisBT.length) {
             return false;
         }
         return true;
     }
     
     private void startCheck() {
         
         mTimer_CheckResult = new Timer();
         TimerTask task = new TimerTask() {
            
            @Override
            public void run() {
                // TODO Auto-generated method stub
                if (isSystemTest) {
                    mHandler_CheckResult.sendEmptyMessage(MSG_CHECK_RESULT);
                }
            }
        };
        mTimer_CheckResult.schedule(task, 500, 500);
        
     }
    
    private void getWifiinfo() {
        mWifiManager.getConnectionInfo();
    }
    
    private void handleWifiEvent(Context context, Intent intent) {
        String action = intent.getAction();
        Log.i("meilianggang", "action = " + action);
        StringBuilder strBuilder = new StringBuilder();
        //System.out.println("tangjun handle wifi action = " + action);
        if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(action)) {
            updateWifiState(intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,
                    WifiManager.WIFI_STATE_UNKNOWN));
            Log.i("meilianggang", "updateWifiState");
        } else if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(action)) {
            List<ScanResult> results = mWifiManager.getScanResults();
            System.out.println("tangjun handle wifi : scanResult.length = " + results.size());
            
            if (results.size()!=0)
            {
                mCanScanWIFI=true;
            }
            
            scanedSsid.clear();
            
            if (!checkAllWifiSsidExist(ssidsWifi, results)) {
                isExistAll_wifi = false;
            } else {
                isExistAll_wifi = true;
            }
            
//            StringBuilder strBuilder = new StringBuilder("\n");
            int wifiCount = 0;
            for (ScanResult scanResult : results) {
                System.out.println("tangjun handle wifi : name = " + scanResult.SSID);
                for (int i = 0; i < ssidsWifi.length; i++) {
                    if (scanResult.SSID.equals(ssidsWifi[i]) && !isScaned(scanResult.SSID)) {
                        scanedSsid.add(scanResult.SSID);
                        
                        wifiCount++;
                        strBuilder.append(getString(R.string.SSID) + scanResult.SSID + getString(R.string.RSSI) + scanResult.level + "dbm");
                        
                        if (isSystemTest) {
                            boolean isPass = false;
                            if (checkWifiFormat()) {
                                isPass = checkWifiErrorResult(scanResult.SSID, scanResult.level);
                                if (!isPass) {
                                    strBuilder.append(getString(R.string.RSSIFail));
                                    isWIFISsidTestOK = false;
                                } else {
                                    strBuilder.append(getString(R.string.RSSIPass));
                                    isWIFISsidTestOK = true;
                                }
                            }
                        }
                        strBuilder.append("\n");
                    }
                }
            }
            
            for (ScanResult scanResult : results) {
                
                if (wifiCount >= MAX_COUNT_DEV_DISPLAY) {
                    break;
                }
                
                boolean ssidExist = false;
                for (int i = 0; i < ssidsWifi.length; i++) {
                    if (scanResult.SSID.equals(ssidsWifi[i])) {
                        ssidExist = true;
                        break;
                    }
                }
                if (!ssidExist && !isScaned(scanResult.SSID)) {
                    strBuilder.append(getString(R.string.SSID) + scanResult.SSID + getString(R.string.RSSI) + scanResult.level + "dbm");
//                    if (CheckRSSIResult(WIFI_NODEFINE_BASE_LINE,scanResult.level)) 
//                    {
//                        strBuilder.append(getString(R.string.RSSIPass));
//                        isWIFISsidTestOK = true;
//                    }
                    strBuilder.append("\n");
                    scanedSsid.add(scanResult.SSID);
                    wifiCount++;
                }
            }
            
//            String tmpStr = this.getString(R.string.SERVICEMENU_OPEN_TXT)
//                    + "\n"
//                    + this.getString(R.string.SERVICEMENU_SCAN_RESULT_TXT)
//                    + results.size();
//            is_pass = false;
//            if (results.size() > 0) {
//                is_pass = true;
//                tmpStr += "\n"
//                        + this.getString(R.string.SERVICEMENU_TEST_RESULT_TXT);
//            }
//            wifiInfosTv.setText(tmpStr);
            //wifiInfosTv.setText(strBuilder.toString());
            Log.i("meilianggang", "results.size() = " + results.size());
            
            if (isExistAll_wifi && isWIFISsidTestOK) {
                resultWifiOK = true;
            } else {
                resultWifiOK = false;
            }

                     isWifiScanned = true;
        }

            // chenkang add for displaying wifi hardware & firmware info, etc.
            if (isWifiScanned) {
                final StringBuilder sb = new StringBuilder("");
                InputStreamReader input = null;

                Log.d(TAG, "before ProcessBuilder...");

                try {
                    java.lang.Process info_read = new ProcessBuilder("/system/bin/cat", "/sys/module/bcmdhd/parameters/info_string").start();
                    input = new InputStreamReader(info_read.getInputStream());

                    int num;
                    char[] buf = new char[128];
                    while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);

                    Log.d(TAG, "Get winfo info: " + sb.toString());

                } catch (IOException e) {
                    Log.e(TAG, "Error running cat", e);
                } finally {
                    if (input != null) try { input.close(); } catch (IOException e) {}
                }

                if (!"".equals(sb.toString())) {
                    strBuilder.append("\n");
                }
                strBuilder.append(sb);
            }
            wifiInfosTv.setText(strBuilder.toString());
            // chenkang add end

    }
    
    List<String> scanedSsid = new ArrayList<String>();
    private boolean isScaned(String ssid) {
        return scanedSsid.contains(ssid);
    }
    
    private void handleBluetoothEvent(Context context, Intent intent) {
        if (!checkAllBTSsidExist()) {
            isExistAll_bt = false;
        } else {
            isExistAll_bt = true;
        }
        
        String action = intent.getAction();
        Log.i("TAG", "action = " + action);
        if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
                updateBlueToothState(intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR));
            Log.i("TAG", "updateBlueToothState");

        } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
        } else if(BluetoothDevice.ACTION_FOUND.equals(action)) {
            mdeviceCount_BT++;
            updateBTInfoSet(intent);
//            mBTDevicesInfo +=  "\n" + getBTDevInfo(intent); // this.getString(R.string.SERVICEMENU_BT_SCAN_RESULT_TXT) + mdeviceCount_BT;
//            tmpStr +=  "\n" + this.getString(R.string.SERVICEMENU_BT_TEST_RESULT_TXT); 
            btDevInfosTv.setText(buildAllBTInfo());
            Log.i("TAG", "results.size() = " + mdeviceCount_BT);

        } /*else if(BluetoothDevice.ACTION_DISAPPEARED.equals(action)) {
            if(mdeviceCount_BT > 0) {
                mdeviceCount_BT--;
                updateBTInfoSet(intent);
            }
//            String tmpStr = this.getString(R.string.SERVICEMENU_BT_OPEN_TXT) + "\n" + this.getString(R.string.SERVICEMENU_BT_SCAN_RESULT_TXT) + mdeviceCount_BT;
//            tmpStr +=  "\n" + this.getString(R.string.SERVICEMENU_BT_TEST_RESULT_TXT); 
//            mBTDevicesInfo =  "\n" + getBTDevInfo(intent);
            btDevInfosTv.setText(buildAllBTInfo());
            Log.i("TAG", "results.size() = " + mdeviceCount_BT);

        }
        */
        if (isExistAll_bt && isBTSsidTestOK) {
            resultBTOK = true;
        } else {
            resultBTOK = false;
        }
    }
    
    class BTInfo {
        String name;
        String address;
        short rssi;
        
        BTInfo(String name, String address, short rssi) {
            this.name = name;
            this.address = address;
            this.rssi = rssi;
        }
        
        @Override
        public int hashCode() {
            return address.hashCode();
        }
        
        @Override
        public boolean equals(Object o) {
            if (o instanceof BTInfo) {
                BTInfo other = (BTInfo) o;
                if (other.address.equals(address)) {
                    return true;
                } else {
                    return false;
                }
            }
            return false;
        }
    }
    
    private Set<BTInfo> mBTInfoSet = new HashSet<BTInfo>();
    private void updateBTInfoSet(Intent intent) {
        String btName = null;
        String btAddr = null;
        short btRssi = 0;
        String action = intent.getAction();
        // 从Intent得到blueDevice对象
        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        if (device == null) {
            return;
        }
        // 设备名称
        btName = device.getName();
        // 设备地址
        btAddr = device.getAddress();
        // 信号强度。
        btRssi = intent.getExtras().getShort(BluetoothDevice.EXTRA_RSSI);
        // 当设备开始扫描时。
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                mBTInfoSet.add(new BTInfo(btName, btAddr, btRssi));
            }
        } /*else if (BluetoothDevice.ACTION_DISAPPEARED.equals(action)) {
            if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
                mBTInfoSet.remove(new BTInfo(btName, btAddr, btRssi));
            }
        }
        */
        if (mBTInfoSet.size()!=0)
        {
            mCanScanBT=true;
        }
    }
    
    private boolean checkAllBTSsidExist() {
        if (ssidsBT != null && ssidsBT.length == 1 && ssidsBT[0].trim().length() == 0) {
            return true;
        }
        for (String ssid : ssidsBT) {
            System.out.println("tangjun bt ssid=" + ssid);
            boolean isExist = false;
            for (BTInfo info : mBTInfoSet) {
                if (ssid.equals(info.name)) {
                    isExist = true;
                }
            }
            if (!isExist) {
                return false;
            }
        }
        return true;
    }
    
    protected boolean CheckRSSIResult(int baseline, int actual) {        
         return Math.abs(baseline)>Math.abs(actual)?true:false;        
     }
    
    private String buildAllBTInfo() {
        StringBuilder builder = new StringBuilder();
        int btCount = 0;
        
//        return builder.toString();
        for (int i = 0; i < ssidsBT.length; i++) {
            for (BTInfo btInfo : mBTInfoSet) {
                try {
                    if (ssidsBT[i].equals(btInfo.name)) {
                        builder.append(getString(R.string.SSID)).append(btInfo.name).append(getString(R.string.RSSI)).append(btInfo.rssi).append("dbm");
                        if (isSystemTest) {
                            int baseline = Integer.parseInt(rssisBT[i]);
                            int actual = btInfo.rssi;
//                            if (!checkErrorResult(expect, actual, valueBTRssiErrorLimitation)) {
                            if (!CheckRSSIResult(baseline, actual)) {
                                builder.append(getString(R.string.RSSIFail));
                                isBTSsidTestOK = false;
                            } else {
                                builder.append(getString(R.string.RSSIPass));
                                isBTSsidTestOK = true;
                            }
                        }
                        Log.i("TAG", "btInfo.name = " + btInfo.name+"btInfo.rssi:"+btInfo.rssi);
                        builder.append("\n");
                        btCount++;
                    }
                } catch (Exception e) {
                    // TODO: handle exception
                    continue;
                }
            }
        }
        Iterator<BTInfo> it = mBTInfoSet.iterator();
        while (it.hasNext()) {
            if (btCount >= MAX_COUNT_DEV_DISPLAY) {
                break;
            }
            try {
                BTInfo btInfo = it.next();
                boolean isExist = false;
                for (String ssid : ssidsBT) {
                    if (btInfo.name.equals(ssid)) {
                        isExist = true;
                    }
                }
                if (!isExist) {
                    btCount++;
                    Log.i("TAG", "btInfo.name = " + btInfo.name+"btInfo.rssi:"+btInfo.rssi);
                    builder.append(getString(R.string.SSID)).append(btInfo.name).append(getString(R.string.RSSI)).append(btInfo.rssi).append("dbm");
//                    if (CheckRSSIResult(BT_NODEFINE_BASE_LINE, btInfo.rssi)) 
//                    {
//                        builder.append(getString(R.string.RSSIPass));
//                        isBTSsidTestOK = true;
//                    }
                    
                    builder.append("\n");
                }
            } catch (Exception e) {
                // TODO: handle exception
                continue;
            }
        }
        return builder.toString();
    }
    
    private void updateBlueToothState(int state) {
        switch (state) {
            case BluetoothAdapter.STATE_ON:
            btLabelText.setText(this.getString(R.string.SERVICEMENU_BT_OPEN_TXT));
            startScanning(false);
            return; 
            case BluetoothAdapter.STATE_OFF:
            btLabelText.setText(this.getString(R.string.SERVICEMENU_BT_TEST_RESULT_FAIL_TXT));
            break;
        }
    }
    
    void startScanning(boolean force) {
        if (!mAdapter_BT.isDiscovering()) {
            if (!force) {
            // Don't scan more than frequently than SCAN_EXPIRATION_MS,
            // unless forced
            if (mLastScan + SCAN_EXPIRATION_MS > System.currentTimeMillis()) {
                return;
            }
            }

            if (mAdapter_BT.startDiscovery()) {
            mLastScan = System.currentTimeMillis();
            }
        }
    }

    private void updateWifiState(int state) {
        switch (state) {
        case WifiManager.WIFI_STATE_ENABLED:
            wifiInfosTv.setText(this.getString(R.string.SERVICEMENU_OPEN_TXT));
            mScanner_Wifi.resume();
            return; // not break, to avoid the call to pause() below

        case WifiManager.WIFI_STATE_ENABLING:
            break;

        case WifiManager.WIFI_STATE_DISABLED:
            wifiInfosTv.setText(this
                    .getString(R.string.SERVICEMENU_TEST_RESULT_FAIL_TXT));
            break;
        }

        mScanner_Wifi.pause();
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(mReceiver_Wifi, mFilter_Wifi, "permission.CIT_ALLOW_BROADCAST", null);
        mTimer_Wifi = new Timer();
        mTimer_Wifi.schedule(new TimerTask() {
            @Override
            public void run() {
                mHandler_Wifi.sendEmptyMessage(SET_WIFI_STATUS);
            }

        }, 1000);
        
        registerReceiver(mReceiver_BT, mFilter_BT, "permission.CIT_ALLOW_BROADCAST", null);
        mTimer_BT = new Timer();
        mTimer_BT.schedule(new TimerTask(){
            @Override
            public void run() {
                mHandler_BT.sendEmptyMessage(SET_BT_STATUS);
            }
    
        }, 1000);
        
        // check result
        startCheck();
    }
    
    @Override
    public void onPause() {
        super.onPause();
        unregisterReceiver(mReceiver_Wifi);
        unregisterReceiver(mReceiver_BT);
        mScanner_Wifi.pause();
        if (mTimer_CheckResult != null) {
            mTimer_CheckResult.cancel();
        }
    }
    
    private class Scanner extends Handler {
        private int mRetry = 0;

        void resume() {
            if (!hasMessages(0)) {
                sendEmptyMessage(0);
            }
        }

        void forceScan() {
            removeMessages(0);
            sendEmptyMessage(0);
        }

        void pause() {
            mRetry = 0;
            removeMessages(0);
        }

        @Override
        public void handleMessage(Message message) {
            if (mWifiManager.startScan()) {
                mRetry = 0;
            } else if (++mRetry >= 3) {
                mRetry = 0;
                return;
            }
            sendEmptyMessageDelayed(0, 10 * 1000);
        }
    }
    
    @Override
    public void finish() {
//        updateTempTestcase(TAG_WIFI, resultWifiOK);
//        if (isSystemTest) {
//            try {
//                LogWriter.write(logFileName, tc);
//            } catch (IOException e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            }
//        }
//        
//        updateTempTestcase(TAG_BT, resultBTOK);
//        if (isSystemTest) {
//            try {
//                LogWriter.write(logFileName, tc);
//            } catch (IOException e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            }
//        }
//        
////        boolean isTestOK = isWifiAndBTTestOK();
//        updateTempTestcase(TAG_WIFI_BT, is_pass);
//        if (isSystemTest) {
//            try {
//                LogWriter.write(logFileName, tc);
//            } catch (IOException e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            }
//        }
        
        isLogged = true;
        
        scanedSsid.clear();
        
//        setTestResult();
//        tc.setTestResult(is_pass);
        super.finish();
    }
    
//    private void updateTempTestcase(/*int index, */String name/*, String resInfo*/, boolean result) {
//        SharedPreferences pre = getSharedPreferences(MATApplication.LANGUAGE_PREF, Context.MODE_PRIVATE);
//        String lanPre = pre.getString(MATApplication.LANGUAGE_KEY, "zh");
//        if (lanPre.equals("zh"))
//            name = nameMapping_language.get(name);
////        tc.setTestCaseIndex(index);
//        tc.setTestCaseName(name);
////        tc.setResultInfo(resInfo);
//        tc.setTestResult(result);
//    }
    
    private boolean isWifiAndBTTestOK() {
        return resultBTOK && resultWifiOK;
    }
}
